package com.ktgj.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.pay.payUtil.AliPayUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

@ControllerAdvice
@RestController
@RequestMapping("aliPay")
public class AliPayController {

    //获取支付宝签名
    @GetMapping("getAliPayParam")
    public String getAliPayParam(BigDecimal payMoney, String orderNumber, String notifyUrl) {
        String aliPayParam = "";
        try {
            aliPayParam = AliPayUtil.getAliPayParam2(payMoney, orderNumber, notifyUrl);
        } catch (Exception e) {
            return "error";//获取支付宝支付签名失败
        }
        return aliPayParam;
    }

    //获取支付宝签名（远程）
    @PostMapping("/postAliPayParam")
    public String postAliPayParam(@RequestBody Map<String, Object> map) {
        BigDecimal payMoney = new BigDecimal(map.get("payMoney").toString());
        String orderNumber = map.get("orderNumber").toString();
        String notifyUrl = map.get("notifyUrl").toString();

        String aliPayParam = "";
        try {
            aliPayParam = AliPayUtil.getAliPayParam2(payMoney, orderNumber, notifyUrl);
        } catch (Exception e) {
            return "error";//获取支付宝支付签名失败
        }
        return aliPayParam;
    }

    //支付成功后回调测试(支付宝回调必须是post方式的回调)
    @PostMapping("test")//notifyUrl = "pay/aliPay/test"
    public void test(HttpServletRequest request) {
        boolean bool = false;
        try {
            bool = AliPayUtil.isPaySuccessful(request);
            if (bool)
                System.out.println("支付成功了");
            else
                System.out.println("支付失败了");
        } catch (Exception e) {
            System.out.println("支付回调失败");
        }
    }

    @PostMapping("alipayRefund")
    public AjaxResult aliPayRefund(@RequestBody Map<String,String> map)
    {
        String refundMoney = map.get("refundMoney");
        String orderNumber = map.get("orderNumber");
        String refundNumber = map.get("refundNumber");
        try
        {
            AlipayTradeRefundResponse alipayTradeRefundResponse = AliPayUtil.aliPayRefund(new BigDecimal(refundMoney), orderNumber, refundNumber);
            return AjaxResult.success(alipayTradeRefundResponse);
        } catch (AlipayApiException e)
        {
            e.printStackTrace();
        }
        return AjaxResult.failure(100);
    }

    //验证支付是否成功
    @GetMapping("isPaySuccessful")
    public String isPaySuccessful(HttpServletRequest request) {
        boolean bool = false;
        try {
            bool = AliPayUtil.isPaySuccessful(request);
            if (bool)
                return "true";
            else
                return "false";
        } catch (Exception e) {
            return "error";//支付回调失败
        }
    }


}
